<template>
	<div id="profit">
		<!-- <div class="details" v-show="moduleDetail==0">
			<div class="timeContainer">
				<div class="time" v-text="times[time].text+'盈亏'"></div>
				<img src="~@/assets/images/explain.png" class="explain" @click="showModal">
			</div>
			<div class="detailedProfit">
				<div class="unit">￥</div>
				<div class="number" v-text="totalProfit"></div>
				<div class="empty"></div>
			</div>
			<div class="rate">
				<div v-text="times[time].text+'累计收益率'"></div>
				<div v-text="message.total_profit_rate+'%'"></div>
			</div>
		</div>
		<return-error v-show="moduleDetail==1"></return-error>
		<return-empty v-show="moduleDetail==2"></return-empty>

		<slot></slot>
 -->
		<div v-show="moduleChart==0">
			<div class="charts">
				<div ref="myChart" style="width:100%; height:240px;"></div>
			</div>

			<ul class="legend">
				<li class="label" v-for="item,index in lines" @click="chooseType(item,index)">
					<img :src="item.checked?item.checkedImg:item.uncheckedImg" class="checkBox">
					<p class="text" v-text="item.text"></p>
				</li>
			</ul>

		</div>
		<return-error v-show="moduleChart==1"></return-error>
		<return-empty v-show="moduleChart==2"></return-empty>
		<defeat :defeat-data="defeatData" :type="type" :time="time" :module="moduleDefeat"></defeat>
	</div>
</template>
<script>
	import echarts from 'echarts/lib/echarts'
	import 'echarts/lib/chart/line'
	import 'echarts/lib/component/tooltip'
	import 'echarts/lib/component/grid'
	import RemoteDAO from '@/common/remoteDAO'
	import defeat from './defeat'
	import Jquery from 'jquery'
	import constant from '@/common/constant'
	import tools from '@/common/tools'
	import myPoint from '@/assets/images/myPoint.png'
	import shPoint from '@/assets/images/shPoint.png'
	import szPoint from '@/assets/images/szPoint.png'
	import cybPoint from '@/assets/images/cybPoint.png'

	const option = {
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'line',
							label: {
								backgroundColor: '#6a7985'
							}
						},
						formatter:function(params,ticket,callback){
							let dateString=tooltipDate[params[0].dataIndex]
							let date=dateString.slice(0,4)+'.'+dateString.slice(4,6)+'.'+dateString.slice(6,8)
							if(!params[1]){
								return (date+
					                    '<br/>'+
					                    '<div style="display:inline-block; width:10px; height:10px; border-radius:50%; background:'+params[0].color+'"></div>&nbsp;'+
					                    params[0].seriesName+'：'+
					                    params[0].value+'%'
								)
							}
				            else{
				            	return (date+
					                    '<br/>'+
					                    '<div style="display:inline-block; width:10px; height:10px; border-radius:50%; background:'+params[0].color+'"></div>&nbsp;'+
					                    params[0].seriesName+'：'+
					                    params[0].value+'%'+
					                    '<br/>'+
					                    '<div style="display:inline-block; width:10px; height:10px; border-radius:50%; background:'+params[1].color+'"></div>&nbsp;'+
					                    params[1].seriesName+'：'+
					                    params[1].value+'%'
					            )
				            }
				        },
						backgroundColor:'rgba(0,0,0,0.4)'
					},
					grid: {
						top: '5%',
						left: '0',
						right: '0',
						bottom:'20%',
						containLabel: true
					},
					xAxis: {
						show: true,
						axisLine: {
							show:false
						},
						data: [],
						type: 'category',
						boundaryGap: false,
						axisLabel: {
							textStyle: {
								color: '#999'
							}
						},
						axisTick: {
							show: false
						},
						axisLine:{
							show:true,
							lineStyle:{
								color:'#c9daeb'
							},
							onZero:false
						}
					},
					yAxis: [{
						show: true,
						axisLine: {
							show: false,
							lineStyle:{
								color:'#c9daeb',
								type:'dotted'
							}
						},
						splitLine: {
							show: true,
							interval:10,
							lineStyle: {
								color: ['#c9daeb'],
								type: 'dotted'
							}
						},
						type: 'value',
						axisLabel: {
							textStyle: {
								color: '#999'
							},
							formatter:'{value}%',
							inside:true,
							margin:4,
							textStyle:{
								color:'#999',
								fontSize:10
							}
						},
						axisTick: {
							show: false
						},
						splitNumber:3
					}],
					series: [{
							name: '我',
							type: 'line',
							stack: '总量',
							areaStyle: { normal: {} },
							data: [],
							symbol:'image://'+myPoint,
							symbolSize:15,
							showSymbol:false,
							itemStyle:{
								normal:{
									color:'#fb8a3f'
								}
							},
							areaStyle:{
								normal:{
									opacity:0
								}
							},
							hoverAnimation: false,
							stack: null
						},
						{
							name: '上证',
							type: 'line',
							stack: '总量',
							areaStyle: { normal: {} },
							data: [],
							symbol:'image://'+shPoint,
							symbolSize:15,
							showSymbol:false,
							itemStyle:{
								normal:{
									color:'#2eaaff'
								}
							},
							areaStyle:{
								normal:{
									opacity:0.1
								}
							},
							hoverAnimation: false,
							stack: null
						},
						{
							name: '深证',
							type: 'line',
							stack: '总量',
							areaStyle: { normal: {} },
							data: [],
							symbol:'image://'+szPoint,
							symbolSize:15,
							showSymbol:false,
							itemStyle:{
								normal:{
									color:'#c394ea'
								}
							},
							areaStyle:{
								normal:{
									opacity:0.1
								}
							},
							hoverAnimation: false,
							stack: null
						},
						{
							name: '创业',
							type: 'line',
							stack: '总量',
							areaStyle: { normal: {} },
							data: [],
							symbol:'image://'+cybPoint,
							symbolSize:15,
							showSymbol:false,
							itemStyle:{
								normal:{
									color:'#256fff'
								}
							},
							areaStyle:{
								normal:{
									opacity:0.1
								}
							},
							hoverAnimation: false,
							stack: null
						}
					]
				}

	let dataOption = {
		xAxis: {
			data: []
		},
		series: [{
			data: []
		},{
			data: []
		},{
			data: []
		},{
			data: []
		}]
	}

	let tooltipDate=[]

	export default {
		props: {
			time: {
				type: Number
			},
			totalProfit: {
				type: String
			},
			assetStat : {
				type:Number
			}
		},
		data() {
			return {
				moduleDetail:0,
				moduleChart:0,
				moduleDefeat:0,
				message:{
					total_profit:'',
					total_profit_rate:'',
					time:'',
					tradedate:''
				},
				defeatTmp: {
					my_profit_rate: '',
					sh_profit_rate: '',
					sz_profit_rate: '',
					cyb_profit_rate: ''
				},
				defeatData: [
					{
						name:'shangzheng',
						text:'上证',
						number:''
					},
					{
						name:'shenzheng',
						text:'深证',
						number:''
					},
					{
						name:'chuangye',
						text:'创业',
						number:''
					}
				],
				tooltipDate:[],
				myChart:null,
				typeEvent: ['002002', '002003', '002004', '002005', '002006'],
				times:[
						{
						name:'today',
						text:'今日',
						num:'1',
						monthNum:1
						},
						{
						name: 'curmonth',
						text: '本月',
						num:'30',
						monthNum:1
						},
						{
						name: 'quarter',
						text: '近三个月',
						num:'90',
						monthNum:3
						},
						{
						name: 'halfyear',
						text: '近半年',
						num:'180',
						monthNum:6
						},
						{
						name: 'year',
						text: '今年',
						num:'365',
						monthNum:12
						},
						{
						name: '2016',
						text: '2016',
						num:'366',
						monthNum:12
						}
					],
				lines: [
					{
						name: 'my',
						text: '我',
						checked: true,
						uncheckedImg: require('@/assets/images/box-my-unchecked.png'),
						checkedImg: require('@/assets/images/box-my-checked.png'),
						id: 0
					},
					{
						name: 'shangzheng',
						text: '上证',
						checked: true,
						uncheckedImg: require('@/assets/images/box-shangzheng-unchecked.png'),
						checkedImg: require('@/assets/images/box-shangzheng-checked.png'),
						id: 1
					},
					{
						name: 'shenzheng',
						text: '深证',
						checked: false,
						uncheckedImg: require('@/assets/images/box-shenzheng-unchecked.png'),
						checkedImg: require('@/assets/images/box-shenzheng-checked.png'),
						id: 2
					},
					{
						name: 'chuangye',
						text: '创业',
						checked: false,
						uncheckedImg: require('@/assets/images/box-chuangye-unchecked.png'),
						checkedImg: require('@/assets/images/box-chuangye-checked.png'),
						id: 3
					}
				],
				activeModal:false,
				fadeAnimation:false,
				typeNum:1
			}
		},
		computed:{
			type:function(){
				let index=null
				this.lines.forEach(value=>{
					if(value.checked && this.lines.indexOf(value)!=0){
						index=this.lines.indexOf(value)
					}
				})
				return index
			}
		},
		mounted() {
			setTimeout(()=>{
				this.myChart=echarts.init(this.$refs.myChart)
				this.myChart.setOption(option)
				this.initEvent()
			},20)
		},
		beforeDestroy(){
			echarts.dispose(this.myChart)
			window.removeEventListener('scroll',this.scrollFunction)
		},
		watch:{
			time:function(){
				setTimeout(()=>{
					this.initEvent()
				},0)
			},
			assetStat:function(){
					setTimeout(()=>{
						this.initEvent()
					},0)
			}
		},
		methods: {
			chooseType(item,index){
				if(this.typeNum != index || index==0){
					TDAPP.onEvent(this.typeEvent[index],'');
					TDAPP.send();
				}
				this.typeNum=index

				if(index==0){
					item.checked=!item.checked;
				}
				else{
					if(!item.checked) {
						for(let i = 1; i < 4; i++) {
							this.lines[i].checked = false;
							item.checked = true;
						}
					}
				}
				this.graph();
			},
			graph(){
				let activeOption=JSON.parse(JSON.stringify(dataOption));
				let activeSeries=activeOption.series;
				activeSeries.forEach(value=>{
					if(!this.lines[activeSeries.indexOf(value)].checked){
						value.data=null;
					}
				})
				this.myChart.setOption(activeOption);
			},
			initEvent(){
				this.moduleDetail=0
				this.moduleChart=0
				this.moduleDefeat=0
				let self=this;
				let obj={"pagenum": this.times[this.time].num,"recent": this.times[this.time].name};
				if(this.time==0){
					console.log('profit 今日')
				}
				else{
					RemoteDAO.callZL13100010(obj,self.ZL13100010);
					RemoteDAO.callZL13100011(obj,self.ZL13100011);
				}
			},
			ZL13100010(result){
				if(result.error=='1'){
					this.moduleDetail=1
					this.moduleChart=1
					this.moduleDefeat=1
				}
				else{
					let data=result.data;
					let bigdata=JSON.parse(data).body[0].bigdata;
					let specData=JSON.parse(bigdata).hits.hits;
					if(specData.length==0){
						this.moduleDetail=2
						this.moduleChart=2
						this.moduleDefeat=2
					}
					else{
						let num=specData[specData.length-1]._source.total_profit_rate_total*100;
					    this.message.total_profit_rate=num.toFixed(2);
					    tooltipDate=specData.reduce((pre,cur)=>{
					    	let dateString=cur._source.tradedate.toString()
					    	pre.push(dateString)
					    	return pre
					    },[])
					    tooltipDate.unshift('')
					    dataOption.xAxis.data=specData.reduce((pre,cur)=>{
					    	let dateString=cur._source.tradedate.toString().split('').splice(4,4);
					    	dateString.splice(2,0,'.');
					    	pre.push(dateString.join(''));
					    	return pre;
					    },[]);
					    if(this.time==0 || this.time==1){
					    	dataOption.xAxis.data=this.xDataExpand(dataOption.xAxis.data)
					    }
					    dataOption.xAxis.data.unshift('')
					    dataOption.xAxis.data.push('')
				    	dataOption.series[0].data=specData.reduce((pre,cur)=>{
					    	let num=cur._source.total_profit_rate_total*100;
					    	pre.push(num.toFixed(2));
					    	return pre;
					    },[]);
					    dataOption.series[0].data.unshift(0)

					    this.defeatTmp.my_profit_rate=specData[specData.length-1]._source.total_profit_rate_total;

						this.defeatDataChange();

					    this.graph();
					}
				}
			},
			ZL13100011(result){
				if(result.error=='1'){
					this.moduleChart=1
					this.moduleDefeat=1
				}
				else{
					let data=result.data;
					let bigdata=JSON.parse(data).body[0].bigdata;
					let specData=JSON.parse(bigdata).hits.hits;
					if(specData.length==0){
						this.moduleChart=2
						this.moduleDefeat=2
					}
					else{
						dataOption.series[1].data=specData.reduce((pre,cur)=>{
							let num=cur._source.sh_total_profit_rate*100;
							pre.push(num.toFixed(2));
							return pre;
						},[]);
						dataOption.series[1].data.unshift(0)

						dataOption.series[2].data=specData.reduce((pre,cur)=>{
							let num=cur._source.sz_total_profit_rate*100;
							pre.push(num.toFixed(2));
							return pre;
						},[]);
						dataOption.series[2].data.unshift(0)

						dataOption.series[3].data=specData.reduce((pre,cur)=>{
							let num=cur._source.cyb_total_profit_rate*100;
							pre.push(num.toFixed(2));
							return pre;
						},[]);
						dataOption.series[3].data.unshift(0)

						this.defeatTmp.sh_profit_rate=specData[specData.length-1]._source.sh_total_profit_rate;
						this.defeatTmp.sz_profit_rate=specData[specData.length-1]._source.sz_total_profit_rate;
						this.defeatTmp.cyb_profit_rate=specData[specData.length-1]._source.cyb_total_profit_rate;

						this.defeatDataChange();

						this.graph();
					}
				}
			},
			defeatDataChange () {
				if(this.defeatTmp.my_profit_rate && this.defeatTmp.sh_profit_rate) {
					this.defeatData[0].number=this.defeatTmp.my_profit_rate-this.defeatTmp.sh_profit_rate;
					this.defeatData[1].number=this.defeatTmp.my_profit_rate-this.defeatTmp.sz_profit_rate;
					this.defeatData[2].number=this.defeatTmp.my_profit_rate-this.defeatTmp.cyb_profit_rate;
				}
			},
			xDataExpand (dateArr) {
				const threshHold = 15
				if(dateArr.length > threshHold ) {
					return dateArr
				}

				let count = dateArr.length;
				let month = Number(dateArr[dateArr.length -1].slice(0, 2));
				let date = Number(dateArr[dateArr.length -1].slice(3, 5))
				let now = new Date(2017, month - 1, date);

				now.setDate(now.getDate() + 1);
				while(count < threshHold) {
					dateArr.push(tools.DateFormat(now, 'MM.dd'))
					now.setDate(now.getDate() + 1);
					count++;
				}

				return dateArr
			},
			showModal(){
				this.$emit('showmodal')
			}
		},
		components:{
			defeat
		}
	}
</script>
<style scoped>
	#profit{
		background: #fff;
		padding: 30px 0;
	}
	.details {
		height: 260px;
		box-sizing: border-box;
		background-image: url(~@/assets/images/banner.png);
		background-size: 100% auto;
		background-repeat: no-repeat;
		color: #fff;
		text-align: center;
		padding-top: 32px;
	}

	.time {
		font-size: 24px;
		opacity: 0.8;
	}

	.detailedProfit {
		margin-top: 20px;
		height: 60px;
		display: flex;
		justify-content: center;
		align-items: baseline;
	}


	.unit {
		width: 1px;
		flex-grow: 1;
		font-size: 32px;
		text-align: right;
	}

	.number {
		font-size: 60px;
		line-height: 60px;
		padding: 0 10px;
	}

	.empty{
		width: 1px;
		flex-grow: 1;
	}

	.rate {
		height: 20px;
		margin-top: 30px;
		opacity: 0.8;
		font-size: 24px;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.rate div {
		padding: 0 10px;
	}

	.charts {
		margin-top: 20px;
		padding: 0;
	}

	.fix-top{
		position: fixed;
		top: 88px;
		width: 100%;
		z-index: 19999999;
	}

	.margin-top{
		margin-top: 100px;
	}


	.legend {
		padding: 0 40px;
		display: flex;
		justify-content: space-between;
	}

	.label {
		height: 30px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.label .checkBox {
		height: 100%;
	}

	.label .text {
		font-size: 24px;
		color: #555;
		margin-left: 20px;
	}

	.timeContainer{
		height: 36px;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.explain{
		height: 24px;
		margin-left: 10px;
	}
</style>
